package com.czr.constant;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.czr.dao.service.CzrUserService;
import com.czr.util.JwtUtil;
import com.czr.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    @Resource
    private HttpServletRequest request;

    @Resource
    private CzrUserService czrUserService;

    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        logger.info("进入拦截器 uri:" + request.getRequestURI());
        // 不是controller的方法不拦截
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        if (request.getRequestURI().contains("doc") || request.getRequestURI().contains("swagger")) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        isLogin isLogin = handlerMethod.getMethodAnnotation(isLogin.class);
        if (isLogin != null) {
            return true;
        }
//        Long userId = JwtUtil.getUserIdByToken(request);
        response.setContentType("application/json;charset=UTF-8");
        response. setCharacterEncoding("UTF-8");
        //用户不存在，进行拦截
//        if (userId == null) {
//            logger.error("用户不存在");
//            JSONObject object=new JSONObject();
//            object.put("code",202);
//            object.put("msg","用户未登录或登录已失效!");
//            object.put("data",null);
//            response.getWriter().write(object.toString());
//            response.setStatus(200);
//            return false;
//        }
        String token = request.getHeader(GlobalConstant.HEADER_TOKEN);
        if (StringUtils.isEmpty(token)) {
            JSONObject object=new JSONObject();
            object.put("code",202);
            object.put("msg","用户未登录或登录已失效!");
            object.put("data",null);
            response.getWriter().write(object.toString());
            response.setStatus(200);
            return false;
        }
        if (!refreshToken()) {
            JSONObject object=new JSONObject();
            object.put("code",202);
            object.put("msg","用户未登录或登录已失效!");
            object.put("data",null);
            response.getWriter().write(object.toString());
            response.setStatus(200);
            return false;
        }

        return true;
    }

    /**
     * token自动续期
     *
     * @return 是否刷新成功
     */
    private boolean refreshToken() {
        ValueOperations<Object, Object> valueOperations = redisTemplate.opsForValue();
        String token = request.getHeader(GlobalConstant.HEADER_TOKEN);
        String cacheToken = (String) valueOperations.get(token);
        //请求头中不存在token，返回false
        if (StringUtils.isEmpty(token)) {
            logger.error("请求头中token不存在");
            return false;
        }
        //用户是否登录只根据redis中token是否存在决定，redis中不存在token，返回false
        if (StringUtils.isEmpty(cacheToken)) {
            logger.error("用户未登录");
            return false;
        }
        int hour=24;
        JSONObject jsonObject=JSONObject.parseObject(cacheToken);
        if(jsonObject.getInteger("isLoginType")==3){
            hour=720;
        }
        valueOperations.set(token, cacheToken, hour, TimeUnit.HOURS);
        return true;
    }

}
